<?php
declare(strict_types=1);

namespace app\api\service;

use app\common\model\GroupModel;

class GroupService extends CommonService
{
    public function message(array $params)
    {
        if ($params['type'] == 1) {
            $this->sendTypeMessage($params);
            $this->robotDialog($params);//智能对话
        }


    }

    public function atMessage(array $params,$message = ''){
        $this->send_group_at_msg($params['robot_wxid'], $params['from_wxid'], $params['final_from_wxid'], $params['final_from_name'], $message);
    }

    public function switchData(array $params){
        $tools = new ToolsService();
        switch ($params['msg']) {
            case '菜单':
            case '菜单列表':
                $this->menu($params);
                break;
            case '签到':
                (new SignService())->sign($params);
                break;
            case '智能对话':
                $this->atMessage($params,'点击头像 安特我 就可以智能对话咯！');exit();
                break;
            case '每日简报':
                $this->atMessage($params,'每天早上10点半 我会告诉你哟');exit();
                break;
            case '骚扰电话查询':
                $this->atMessage($params,'发送 电话号码 xxxxxxxx 查询');exit();
                break;
                case '点歌':
                $this->atMessage($params,'发送 点歌 歌名 例如：点歌 李白');exit();
                break;
            case '舔狗日记':
                $tools->dogDiary($params);
                break;
                case '抽签':
                $tools->getDraw($params);
                break;
            case '解签':
                $tools->getOpenDraw($params);
                break;
            case '抖音':
            case '抖音去水印':
                $this->SendDyMessage($params);
                break;
        }
    }

    public function sendTypeMessage($params){
        $tools = new ToolsService();
        $this->switchData($params);//可选择入口
        $tools->weather($params);//天气
        $tools->sendMusic($params);//点歌
        $tools->constellation($params);//星座
        $tools->checkPhone($params);//手机号查询
        $tools->dyAnalysis($params);//抖音简析
    }



    public function robotDialog(array $params)
    {

        //$ret = $this->atRobot($params);
        $ret = $this->atLowRobot($params);
        if ($ret) {//确认是有安特的情况 进行判断
            if ($ret['at_wxid'] === $params['robot_wxid']) {//确定安特的是机器人 进行回复
                $msg = '安特就是喜欢我！';
                if ($ret['msg']) {//这里设置关键词 没有 进行智能回复
                    $params['msg'] = $ret['msg'];
                    $this->switchData($params);//可选择入口
                   $this->sendTypeMessage($params);
                    if('你的主人是' === $ret['msg']|| '你的主人是谁' === $ret['msg'] ||'你的主人' === $ret['msg'] || '你的主子是谁' === $ret['msg']){
                        $msg = "当然是帅气迷人的`Poison`咯";
                    }else{
                        $url = config('url.robot_url') . $ret['msg'];
                        $res = json_decode(file_get_contents($url), true);
                        if (isset($res['result']) && $res['result'] == 0) {
                            $msg = str_replace('','{br}',$res['content']);
                        } else {
                            $msg = '维护中...';
                        }
                    }
                }
                $this->send_group_at_msg($params['robot_wxid'], $params['from_wxid'], $params['final_from_wxid'], $params['final_from_name'], $msg);
            }

        }

    }

    public function atRobot(array $params): array
    {
        try {
            //开始截取
            $data = [];
            $msg = trim($params['msg'], "\[\]");
            if (strpos('@at,', $msg) == 0) {//是安特 进入
                $msg = strReplaceMessage('at,', $msg);
                $arr = explode(',wxid=]', $msg);
                $str = explode(',', $arr[1]);
                $data['msg'] = trim($str[0]);
                $data['at_wxid'] = trim(explode('=', $str[1])[1], "\[\]");
            }
            return $data;
        }catch (\Exception $e){
            return $this->atLowRobot($params);
        }
    }
    public function atLowRobot(array $params):array
    {
        try {
            $msg = trim($params['msg'], "\[\]");
            $str = explode(']',$msg);
            $data['msg'] = strReplaceMessage(' ',$str[1],'');
            $arr = explode(',',$str[0]);
            if(strpos('@at',$arr[0]) == 0){
                if(empty($arr[3])){
                    $data['at_wxid'] = trim(explode('=',$arr[2])[1]);
                }else{
                    return $this->atRobot($params);
                }

            }
            return $data;
        }catch (\Exception $e){
            return $this->atRobot($params);
        }

    }

    public function menu(array $params)
    {
        $message = " --------技能列表--------\r" .
            " [爱心] 签到 | 天气 | 星座\r" .
            " [爱心] 点歌 | 抽签 | 智能对话\r" .
            " [心碎] 舔狗日记 | 骚扰电话查询\r" .
            " [爱心] 进群欢迎 | 退群提醒\r" .
            " [爱心] 每日简报 | 抖音去水印 \r" .
            " --------技能列表--------";
        $this->send_text_msg($params['robot_wxid'], $params['from_wxid'], $message);
        exit();
    }

    public function invitationGroup(array $params)
    {
        $group = new GroupModel();
        $groupData = $group->getGroupDataByStatus($params);
        foreach ($groupData as $v) {
            if ($v['nickname'] === $params['msg']) {
                return $this->invite_in_group($params['robot_wxid'], $v['wxid'], $params['final_from_wxid']);
            }
        }
        return false;
    }

    /**新人进群
     * @param array $params
     */
    public function addMember(array $params)
    {
        if ($this->checkGroup($params)) {//验证通过 发送消息
            $message = "欢迎 `" . $params['final_from_name'] . "`加入大家庭 ~\r"
                . "    大家掌声欢迎 ~";
            $this->send_text_msg($params['robot_wxid'], $params['from_wxid'], $message);
        }
    }

    /**退群事件
     * @param array $params
     */
    public function outMember(array $params)
    {
        if ($this->checkGroup($params)) {//验证通过 发送消息
            if($params['robot_wxid'] === $params['msg']['member_wxid']){
                (new GroupModel())->where('wxid',$params['from_wxid'])->delete();
            }else{
                $message = "终有离别时~\r"
                    . "  有缘江湖再见！\r"
                    . "    `" . $params['final_from_name'] . '`退出群聊';
                $this->send_text_msg($params['robot_wxid'], $params['from_wxid'], $message);
            }
        }
    }

    public function agreeGroupInviteData(array $params)
    {
       $msg = trim($params['msg'],"{\}");
       $arr = explode(',',$msg);
       $img = trim(explode(':',$arr[0])[1].":".explode(':',$arr[0])[2],'"');
       $nickname = trim(explode(':',$arr[1])[1],'"\\');
        $groupModel = new GroupModel();
        $groupModel->insert(
            [
                'nickname'=>$nickname,
                'robot_wxid'=>$params['robot_wxid'],
                'memberCount'=>100,
                'wxid'=>'1111',
                'headimgurl'=>$img,
                'isManager'=>0,
                'status'=>1
            ]
        );
        $this->agree_group_invite($params['robot_wxid'], $params['msg']);
    }

    public function SendDyMessage(array $params)
    {
        $message = "打开抖音分享 -> 最底下一排 -> 复制链接 粘贴在群里 就ok啦～";
        $this->send_text_msg($params['robot_wxid'], $params['from_wxid'], $message);exit();
    }

    /** 检查群是否正常使用
     * @param array $params
     */
    public function checkGroup(array $params): bool
    {
        return true;//暂时全部开放
        $where = [
            'wxid' => $params['from_wxid'],
            'status' => 1,
        ];
        $ret = (new GroupModel())->getOneGroupData($where);
        if (!$ret) return false;
        return true;
    }

}